Imports System.Data.SqlClient
Imports System.Drawing
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.XtraEditors
Imports DevExpress.XtraScheduler
Imports DevExpress.XtraScheduler.UI
'--- Created Date On : 29-Sep-2010 (Gyana)

Public Class frmRegistration
    Dim mlngRecordID As Long ' This is the VisitId
    Dim blnUnload As Boolean
    Dim mblnChanged As Boolean
    Dim mblnActivate As Boolean
    Dim mblnCancelDisplay As Boolean

    Dim mintPatientId As Integer
    Public mstrFrmName As String = ""

    Public Sub New(ByVal IdVisit As Integer, Optional ByVal IdPatient As Integer = -1)
        MyBase.New()

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        mlngRecordID = IdVisit
        mintPatientId = IdPatient

    End Sub

    Private Sub frmRegistration_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Try
            If mblnActivate = True Then
                mblnActivate = False

                'Fill Doctor combo
                Call PopulateLookupDX(lkDoctor, "Name", "PracticeId", "tblPracticeInfo JOIN tblUsers ON tblPracticeInfo.UserId=tblUsers.UserId", "PracticeId,(FirstName + ' ' + LastName) AS Name", , "(FirstName + ' ' + LastName)")
                'Fill Patient status
                Call PopulateLookupDX(lkStatus, "Patient Status", "PatientStatusId", "LtblPatientStatus", "PatientStatusId,PatientStatus As [Patient Status]", , "PatientStatusId")
                'Fill Appointment Type
                Call PopulateLookupDX(lkAppointmentType, "Appointment Type", "AppointmentTypeId", "LtblAppointmentType", "AppointmentTypeId,AppointmentType As [Appointment Type]", , "AppointmentType")
                'Fill Location
                Call PopulateLookupDX(lkLocation, "Visit Location", "VisitLocationId", "LtblVisitLocation", "VisitLocationId,VisitLocation As [Visit Location]", , "VisitLocation")

                lkDoctor.ItemIndex = 0
                dtTime.EditValue = Now
                lkStatus.ItemIndex = 0
                If mstrFrmName <> "Appointment" Then
                    lkAppointmentType.EditValue = CInt(Val(strRecordID("LtblAppointmentType", "AppointmentTypeID", "AppointmentType Like 'Walk In'")))
                Else
                    lkAppointmentType.EditValue = CInt(Val(strRecordID("LtblAppointmentType", "AppointmentTypeID", "AppointmentType Like 'Appointment'")))
                End If

                lkLocation.ItemIndex = 0

                If mlngRecordID = -1 Then 'show default location as office
                    lkLocation.Text = "Office"
                    'Dim dt As DataTable
                    'dt = lkLocation.Properties.DataSource
                    'lkLocation.EditValue = dt.Select("Visit Location=" & "'Office'")(0).Item("VisitLocationId")
                End If

                If gintUserLevelId = 1 OrElse gintUserLevelId = 2 Then
                    lkDoctor.EditValue = GetPracticeId(gintUserID)
                    lkDoctor.Enabled = False
                End If

                If mlngRecordID = -1 Then
                    Exit Sub
                End If

                Call DisplayData()
            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmRegistration_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try

            Dim intUnload As DialogResult
            mstrFrmName = ""
            If mblnChanged = True Then
                intUnload = MessageBox.Show("You have not saved your changes to the record. Do you want to save your changes now?", gstrMessage, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1)
                If intUnload = Windows.Forms.DialogResult.Cancel Then
                    e.Cancel = True : Exit Sub
                ElseIf intUnload = Windows.Forms.DialogResult.Yes Then
                    blnUnload = True
                    If blnSaveRecords() = False Then
                        e.Cancel = True
                        blnUnload = False
                        Exit Sub
                    End If
                    mblnChanged = False
                End If
            End If
            blnUnload = False

        Catch ex As Exception
            blnUnload = False
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub frmRegistration_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try

            Call SetImageControl(Me)
            Me.Icon = System.Drawing.Icon.FromHandle(CType(mdiMain.imgFormIcons.Images(2), Bitmap).GetHicon())
            Call GetAccessPermission(Me, "frmRegistration")

            mblnActivate = True
            mblnChanged = False

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub


    Private Sub DisplayData()
        'Display data in form fields.
        Dim dsTemp As DataSet
        Dim strQuery As String
        Try
            strQuery = "SELECT * FROM tblVisits WHERE VisitId = " & mlngRecordID
            dsTemp = FillDataSet(strQuery)

            With dsTemp.Tables(0)
                If .Rows.Count > 0 Then
                    lkDoctor.EditValue = CInt(.Rows(0).Item("PracticeId"))
                    dtTime.EditValue = .Rows(0).Item("VisitDate")
                    lkStatus.EditValue = CInt(.Rows(0).Item("PatientStatusId"))
                    lkAppointmentType.EditValue = CInt(.Rows(0).Item("AppointmentTypeId"))
                    lkLocation.EditValue = CInt(.Rows(0).Item("VisitLocationId"))

                End If
            End With

            dsTemp.Dispose()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Me.Close()
    End Sub

    Private Function IsValidEntry() As Boolean
        'Here check valid entry of fields
        Dim strMsg As String = ""
        IsValidEntry = False

        If IsDBNullOrNothing(lkDoctor.EditValue) Then
            strMsg = "Please select Doctor"
            lkDoctor.Focus()
        ElseIf IsDBNullOrNothing(dtTime.EditValue) Then
            strMsg = "Please enter Time"
            dtTime.Focus()
        ElseIf IsDBNullOrNothing(lkStatus.EditValue) Then
            strMsg = "Please select Status"
            lkStatus.Focus()
        ElseIf IsDBNullOrNothing(lkAppointmentType.EditValue) Then
            strMsg = "Please select Appointment Type"
            lkAppointmentType.Focus()
        ElseIf IsDBNullOrNothing(lkLocation.EditValue) Then
            strMsg = "Please select Location"
            lkLocation.Focus()
        End If

        If Trim(strMsg) <> "" Then
            IsValidEntry = False
            MessageBox.Show(strMsg, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        Else
            IsValidEntry = True
        End If
    End Function

    Private Function blnSaveRecords() As Boolean
        Dim blnIsTransactionOpen As Boolean
        Dim strQuery As String
        Try
            blnSaveRecords = False

            If IsValidEntry() = False Then
                Exit Function
            End If

            gtrnWebPlusMed = gconWebPlusMed.BeginTransaction
            blnIsTransactionOpen = True

            If Val(strRecordID("tblVisits", "VisitId", "VisitId=" & mlngRecordID)) > 0 Then
                'Update registration in tblVisits table if VisitId>0
                strQuery = "PracticeId=" & lkDoctor.EditValue & _
                            ",VisitDate='" & dtTime.EditValue & "'" & _
                            ",VisitLocationId=" & lkLocation.EditValue & _
                            ",AppointmentTypeId=" & lkAppointmentType.EditValue & _
                            ",PatientStatusId=" & lkStatus.EditValue
                'Format(dtTime.EditValue, "MM-dd-yyyy hh:mm tt") & "'" & _
                Call UpdateTable("tblVisits", strQuery, "VisitId=" & mlngRecordID)
            Else
                'Insert registration in tblVisits table if VisitId<=0
                strQuery = mintPatientId & _
                           "," & lkDoctor.EditValue & _
                           ",'" & dtTime.EditValue & "'" & _
                            "," & lkLocation.EditValue & _
                            "," & lkAppointmentType.EditValue & _
                            "," & lkStatus.EditValue & _
                            ",0"
                Call InsertintoTable("tblVisits", strQuery, "PatientId,PracticeId,VisitDate,VisitLocationId,AppointmentTypeId,PatientStatusId,VisitStatus")
            End If

            blnSaveRecords = True

            gtrnWebPlusMed.Commit()
            blnIsTransactionOpen = False
            mblnChanged = False

        Catch ex As Exception
            If blnIsTransactionOpen = True Then
                gtrnWebPlusMed.Rollback()
            End If
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Function
    Public Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Try
            If blnSaveRecords() = False Then Exit Sub
            'Dim frmTempShowAppointment As New frmShowAppointment
            'With frmTempShowAppointment
            '    .grdPatientWaiting.BeginUpdate()
            '    .PopulatePatientWaitingGrid()
            '    .grdPatientWaiting.EndUpdate()
            'End With
            gblnIsRefreshed = True
            Me.Close()

        Catch ex As Exception
            MessageBox.Show(ex.Message, gstrMessage, MessageBoxButtons.OK, MessageBoxIcon.Error)
            Call AddErrorLog("Error " & Err.Number & " (" & Err.Description & ") in Procedure " & _
                 Reflection.MethodBase.GetCurrentMethod.Name & " Of " & Me.Name)
        End Try
    End Sub

    Private Sub lkControls_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lkStatus.TextChanged, lkLocation.TextChanged, lkDoctor.TextChanged, lkAppointmentType.TextChanged
        mblnChanged = True
    End Sub

    Private Sub dtTime_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtTime.TextChanged
        mblnChanged = True
    End Sub
End Class
